package com.lishe.lishe.lishe.module.myorder.adapter;

import android.app.Activity;
import android.content.Intent;
import android.graphics.Paint;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.BaseExpandableListAdapter;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.RelativeLayout;
import android.widget.TextView;

import com.lishe.base.common.config.Constants;
import com.lishe.lishe.Imageloader.ImageLoaderUtils;
import com.lishe.lishe.R;
import com.lishe.lishe.lishe.common.Arith;
import com.lishe.lishe.lishe.module.myorder.activity.LogisticsActivity;
import com.lishe.lishe.lishe.module.myorder.activity.OrderDetailActivity;
import com.lishe.lishe.lishe.module.myorder.bean.OrderListResponse;
import com.lishe.lishe.lishe.module.myorder.interfase.OrderButtonClickListener;
import com.lishe.lishe.lishe.module.myorder.view.RemindSendDialog;
import com.lishe.lishe.lishe.module.pay.activity.PayActivity;
import com.lishe.lishe.lishe.utils.DefaultCountDownTimer;
import com.lishe.lishe.lishe.utils.FormatUtil;
import com.lishe.lishe.lishe.utils.TimeUtils;

import java.util.List;

/**
 * 标    题：
 * 功能描述：
 * 作    者：zouxx
 * 创建时间：2018/8/24
 */

public class OrderAdapter extends BaseExpandableListAdapter {

    private List<OrderListResponse.DataBean.ListBean> listBeans;
    private Activity context;
    private OrderButtonClickListener listener;
    private final String[] orderBtnType;
    private DefaultCountDownTimer timer;

    public OrderAdapter(Activity activity, List<OrderListResponse.DataBean.ListBean> listBeans) {
        this.context = activity;
        this.listBeans = listBeans;
        orderBtnType = context.getResources().getStringArray(R.array.order_btn_type);
    }

    @Override
    public int getGroupCount() {
        return listBeans != null ? listBeans.size() : 0;
    }

    @Override
    public int getChildrenCount(int groupPosition) {
        return listBeans.get(groupPosition).products != null ? listBeans.get(groupPosition).products.size() : 0;
    }

    @Override
    public Object getGroup(int groupPosition) {
        return listBeans.get(groupPosition);
    }

    @Override
    public Object getChild(int groupPosition, int childPosition) {
        return listBeans.get(groupPosition).products.get(childPosition);
    }

    @Override
    public long getGroupId(int groupPosition) {
        return groupPosition;
    }

    @Override
    public long getChildId(int groupPosition, int childPosition) {
        return childPosition;
    }

    @Override
    public boolean hasStableIds() {
        return false;
    }

    @Override
    public View getGroupView(int groupPosition, boolean isExpanded, View convertView, ViewGroup parent) {
        OrderTopViewHolder holder;
        if (convertView == null) {
            convertView = LayoutInflater.from(context).inflate(R.layout.item_order_goods_top, null);
            holder = new OrderTopViewHolder(convertView);
            convertView.setTag(holder);
        } else {
            holder = (OrderTopViewHolder) convertView.getTag();
        }
        OrderListResponse.DataBean.ListBean listBean = listBeans.get(groupPosition);
        holder.mOrderType.setText(listBean.getOrderStatusText());
        holder.mOrderTime.setText(TimeUtils.longToyyyyMMddHHmmss(Long.parseLong(listBean.created_time) * 1000));
        return convertView;
    }

    @Override
    public View getChildView(int groupPosition, int childPosition, boolean isLastChild, View convertView, ViewGroup parent) {
        OrderInfoViewHolder viewHolder;
        if (convertView == null) {
            convertView = LayoutInflater.from(context).inflate(R.layout.item_order_goods, null);
            viewHolder = new OrderInfoViewHolder(convertView);
            convertView.setTag(viewHolder);
        } else {
            viewHolder = (OrderInfoViewHolder) convertView.getTag();
            timer = (DefaultCountDownTimer) viewHolder.mPayButton.getTag();
            if (timer != null) {
                timer.cancel();
                timer = null;
            }
        }
        final OrderListResponse.DataBean.ListBean listBean = listBeans.get(groupPosition);
        if (listBean.order_status == 4) {
            if (listBean.getTimeLeftToPay() >= 1000) {

                try {   //倒计时
                    DefaultCountDownTimer timer = new DefaultCountDownTimer(viewHolder.mPayButton, "付款 ",
                            "", listBean.getTimeLeftToPay(), 1000, () -> {
                        if (listener!=null){
                            listener.updateUI(groupPosition);
                        }
                    });
                    timer.start();
                    viewHolder.mPayButton.setTag(timer);
                } catch (Exception e) {
                    e.printStackTrace();
                }
            }else {
                if (listener!=null){
                    listener.updateUI(groupPosition);
                }
            }
        }
        viewHolder.mLlBottom.setVisibility(isLastChild ? View.VISIBLE : View.GONE);
        setGoodsInfo(viewHolder, listBean, childPosition);
        setPayViewVisible(listBean, viewHolder, orderBtnType);
        setListener(viewHolder, listBean);
        return convertView;
    }

    private void setGoodsInfo(OrderInfoViewHolder viewHolder, OrderListResponse.DataBean.ListBean listBean, int childPosition) {
        OrderListResponse.DataBean.ListBean.ProductsBean goods = listBean.products.get(childPosition);
        ImageLoaderUtils.displayImage(context, goods.pic_path, viewHolder.mGoodsImg);
        viewHolder.mGoodsName.setText(goods.title);
        viewHolder.mGoodsSpec.setText(goods.spec_info);
        viewHolder.mGoodsPrice.setText(goods.price);
        viewHolder.mGoodsCount.setText("x" + goods.num);
        viewHolder.mOriginalPrice.setVisibility(!goods.price.equals(goods.original_price) ? View.VISIBLE : View.GONE);
        viewHolder.mOriginalPrice.setText("¥ " + goods.original_price);
        viewHolder.mOriginalPrice.getPaint().setFlags(Paint.STRIKE_THRU_TEXT_FLAG | Paint.ANTI_ALIAS_FLAG);
        viewHolder.mPayMoney.setText(FormatUtil.numFormat(Arith.mul(Double.parseDouble(listBean.money), 100)));
        viewHolder.mTotalCount.setText(String.format("共%d件", listBean.num));
        viewHolder.mCancleButton.setEnabled(!(listBean.order_status == 5 && listBean.isReminder));
        viewHolder.mCancleButton.setTextColor(listBean.order_status == 5 && listBean.isReminder ?
                context.getResources().getColor(R.color.gray_9) : context.getResources().getColor(R.color.gray_3));
    }

    @Override
    public boolean isChildSelectable(int groupPosition, int childPosition) {
        return true;
    }

    private void setListener(OrderInfoViewHolder holder, OrderListResponse.DataBean.ListBean listBean) {
        holder.mCancleButton.setOnClickListener(v -> {
            if (listBean.order_status == 5) {//
                new RemindSendDialog(context).show();
                listBean.isReminder = true;
                notifyDataSetChanged();
            } else if (listBean.order_status == 7 || listBean.order_status == 8 || listBean.order_status == 9) {
                //已退款 已完成，已退货
                startActivity(listBean, (listBean.products != null && listBean.products.size() > 0) ? listBean.products.get(0).tid : "");
            } else if (listBean.order_status == 4) {// 待付款
                if (listener != null) {
                    listener.showCancelDialog(listBean.payment_id);
                }
            } else if (listBean.order_status == 6) {//待收货
                if (listBean.products != null && listBean.products.size() > 0)
                    LogisticsActivity.jump(context, listBean.products.get(0).tid);
            }
        });
        holder.mPayButton.setOnClickListener(v -> {
            if (listBean.order_status == 4) {// 待付款
                if (listBean.products != null && listBean.products.size() > 0)
                    PayActivity.jump(context, listBean.payment_id, TimeUtils.longToyyyyMMddHHmmss(Long.parseLong(listBean.created_time) * 1000), listBean.money);
            } else if (listBean.order_status == 6) {//待收货
                if (listener != null)
                    listener.showConfirmDialog(listBean.payment_id);
            }
        });
    }

    public void setButtonListener(OrderButtonClickListener listener) {
        this.listener = listener;
    }

    private void startActivity(OrderListResponse.DataBean.ListBean listBean, String tid) {
        Intent i = new Intent(context, OrderDetailActivity.class);
        i.putExtra(Constants.TID, tid);
        i.putExtra(Constants.PAYMENTID, listBean.payment_id);
        i.putExtra(Constants.ISREMINDSEND, listBean.isReminder);
        context.startActivity(i);
    }

    public void setPayViewVisible(OrderListResponse.DataBean.ListBean listBean, OrderInfoViewHolder holder, String[] orderBtnType) {
        switch (listBean.order_status) {
            case 1: //超时失效
            case 2: //用户手动取消
            case 3: //被客服取消
                holder.mRlBottom.setVisibility(View.GONE);
                break;
            case 4:
                holder.mRlBottom.setVisibility(View.VISIBLE);
                holder.mPayButton.setVisibility(View.VISIBLE);
                holder.mCancleButton.setVisibility(View.VISIBLE);
                holder.mCancleButton.setText(orderBtnType[0]);
                holder.mPayButton.setText(orderBtnType[4]);
                break;
            case 5:
                holder.mRlBottom.setVisibility(View.VISIBLE);
                holder.mPayButton.setVisibility(View.GONE);
                holder.mCancleButton.setVisibility(View.VISIBLE);
                holder.mCancleButton.setText(orderBtnType[1]);
                break;
            case 6:
                holder.mRlBottom.setVisibility(View.VISIBLE);
                holder.mPayButton.setVisibility(View.VISIBLE);
                holder.mCancleButton.setVisibility(View.VISIBLE);
                holder.mCancleButton.setText(orderBtnType[2]);
                holder.mPayButton.setText(orderBtnType[3]);
                break;
            case 7:
            case 8:
            case 9:
                holder.mRlBottom.setVisibility(View.VISIBLE);
                holder.mPayButton.setVisibility(View.GONE);
                holder.mCancleButton.setVisibility(View.VISIBLE);
                holder.mCancleButton.setText("查看详情");
                break;
            default:
                holder.mRlBottom.setVisibility(View.GONE);
                break;
        }
    }

    static class OrderTopViewHolder {
        private TextView mOrderTime;
        private TextView mOrderType;

        public OrderTopViewHolder(View view) {
            mOrderTime = (TextView) view.findViewById(R.id.order_time);
            mOrderType = (TextView) view.findViewById(R.id.order_type);
        }
    }

    static class OrderInfoViewHolder {
        private ImageView mGoodsImg;
        private TextView mGoodsName;
        private TextView mGoodsSpec;
        private LinearLayout mLlBottom;
        private TextView mGoodsPrice;
        private TextView mOriginalPrice;
        private TextView mGoodsCount;
        private TextView mTotalCount;
        private TextView mPayMoney;
        private RelativeLayout mRlBottom;
        private TextView mPayButton;
        private TextView mCancleButton;

        public OrderInfoViewHolder(View view) {
            mGoodsImg = (ImageView) view.findViewById(R.id.goods_img);
            mGoodsName = (TextView) view.findViewById(R.id.goods_name);
            mGoodsSpec = (TextView) view.findViewById(R.id.goods_spec);
            mLlBottom = (LinearLayout) view.findViewById(R.id.ll_bottom);
            mGoodsPrice = (TextView) view.findViewById(R.id.goods_price);
            mOriginalPrice = (TextView) view.findViewById(R.id.original_price);
            mGoodsCount = (TextView) view.findViewById(R.id.goods_count);
            mTotalCount = (TextView) view.findViewById(R.id.total_count);
            mPayMoney = (TextView) view.findViewById(R.id.pay_money);
            mRlBottom = (RelativeLayout) view.findViewById(R.id.rl_bottom);
            mPayButton = (TextView) view.findViewById(R.id.pay_button);
            mCancleButton = (TextView) view.findViewById(R.id.cancle_button);
        }
    }
}
